<?php

namespace admin\models;

use admin\traits\ModelStatus;
use ijony\helpers\File;
use ijony\helpers\Folder;
use ijony\helpers\Image;
use Yii;
use yii\helpers\ArrayHelper;
use yii\web\UploadedFile;

/**
 * This is the model class for table "{{%news}}".
 *
 * @property int $id 新闻 ID
 * @property string $title 标题
 * @property string $image 图片
 * @property string $description 简介
 * @property string|null $content 内容
 * @property int $status 状态
 */
class News extends \common\models\News
{

    use ModelStatus;

    const STATUS_DELETE = 0;
    const STATUS_INACTIVE = 1;
    const STATUS_ACTIVE = 9;

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return ArrayHelper::merge(parent::rules(), [
            ['status', 'default', 'value' => self::STATUS_ACTIVE],
            ['status', 'in', 'range' => [self::STATUS_ACTIVE, self::STATUS_INACTIVE, self::STATUS_DELETE]],
        ]);
    }

    /**
     * @param bool $insert
     *
     * @return bool
     */
    public function beforeSave($insert)
    {
        $file = UploadedFile::getInstance($this, 'image');
        if ($file) {
            $this->image = File::newFile($file->getExtension());
        }

        return parent::beforeSave($insert);
    }

    /**
     * @param bool $insert
     * @param array $changedAttributes
     */
    public function afterSave($insert, $changedAttributes)
    {
        parent::afterSave($insert, $changedAttributes);

        $file = UploadedFile::getInstance($this, 'image');
        if ($file) {
            $file->saveAs(Folder::getStatic($this->image));

            if ($this->getOldAttribute('image')) {
                File::delFile(Folder::getStatic($this->getOldAttribute('image')));
            }
        }
    }

    /**
     * @param int $width
     * @param int $height
     *
     * @return mixed|string
     */
    public function getImage($width = 0, $height = 0)
    {
        return Image::getImg($this->image, $width, $height);
    }
}
